package cn.com.lms.business.core.util;

import org.aspectj.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class FileUtils {
    protected static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    /**
     * 创建目录
     *
     * @param dir             目录名称
     * @param createParentDir 如果父目录不存在，是否创建父目录
     * @return
     */
    public static boolean makeDir(String dir, boolean createParentDir) {
        logger.info("dir:{}  createParentDir:{}", dir, createParentDir);
        boolean zResult = false;
        File file = new File(dir);
        if (createParentDir) {
            zResult = file.mkdirs(); // 如果父目录不存在，则创建所有必需的父目录
        } else {
            zResult = file.mkdir(); // 如果父目录不存在，不做处理
        }
        if (!zResult) {
            zResult = file.exists();
        }
        logger.info("zResult:{}", zResult);
        return zResult;
    }

    /**
     * 上传文件到指定的目录
     *
     * @param multipartFile
     * @param directory
     * @return
     */
    public static Map<String, Object> upload(MultipartFile multipartFile, String directory, String uploadPath) throws IOException {
        logger.info("directory:{}", directory);
        Map<String, Object> resultMap = null;
        if (multipartFile == null) {
            return resultMap;
        }
        /*获取文件的名称*/
        String fileName = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return resultMap;
        }
        boolean result = makeDir(directory, true);
        if (!result) {
            return resultMap;
        }
        resultMap = new HashMap<String, Object>();
        resultMap.put("fileName", fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String name = new Date().getTime() + suffix;
        resultMap.put("newFileName", name);
        String filePath = uploadPath + File.separator + name;
        resultMap.put("filePath", filePath);
        String saveFilePath = directory + File.separator + name;
        File newFile = new File(saveFilePath);
        multipartFile.transferTo(newFile);
        logger.info("resultMap:{}", JsonUtil.objToJson(resultMap));
        return resultMap;
    }


}
